package sample;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadFactory;

public class Main extends Application {

//    private static List<File> queue = new ArrayList<>();


    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        VBox root = new VBox();
        root.setStyle("-fx-background-color: #ffffff");

        HBox hBox = new HBox();
        hBox.setPrefHeight(40);
        hBox.setAlignment(Pos.CENTER);

        Button search = new Button("搜索");
        TextField text_FileName = new TextField();
        text_FileName.setPromptText("请输入文件关键字");

        TextField text_searchPath = new TextField();
        text_searchPath.setPromptText("请输入检索地址");

        TextField text_Filepath = new TextField();
        text_Filepath.setPromptText("请输入文件夹父路径");
        Button copy = new Button("移动");

        TableView<File> tableView = new TableView<>();
        tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        tableView.setTableMenuButtonVisible(true);
        VBox.setVgrow(tableView, Priority.ALWAYS);

        TableColumn<File, String> tc_path = new TableColumn<>("路径");
        TableColumn<File, String> tc_name = new TableColumn<>("文件名称");
        tc_path.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<File, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<File, String> param) {
                SimpleStringProperty ssp = new SimpleStringProperty(param.getValue().getFilePath());
                return ssp;
            }
        });
        tc_name.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<File, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<File, String> param) {
                SimpleStringProperty ssp = new SimpleStringProperty(param.getValue().getFileName());
                return ssp;
            }
        });


        tableView.getColumns().add(tc_name);
        tableView.getColumns().add(tc_path);


        hBox.getChildren().addAll(text_searchPath, text_FileName, search, text_Filepath, copy);

        root.getChildren().addAll(hBox, tableView);

        Scene scene = new Scene(root);
        primaryStage.setWidth(800);
        primaryStage.setHeight(800);
        primaryStage.setScene(scene);
        primaryStage.setTitle("文件检索+转移（α 0.01）");
        primaryStage.setAlwaysOnTop(true);
        primaryStage.show();

        //展示弹幕列表
        ObservableList<File> files = FXCollections.observableArrayList();

        FileTask fileTask = new FileTask();
        fileTask.valueProperty().addListener(new ChangeListener<ObservableList<File>>() {
            @Override
            public void changed(ObservableValue<? extends ObservableList<File>> observable, ObservableList<File> oldValue, ObservableList<File> newValue) {
                if (newValue != null) {
                    files.addAll(newValue);
                    tableView.setItems(files);
                    tableView.scrollTo(files.size() - 1);
                    fileTask.cancel();
                }
            }
        });

        //检索文件
        search.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                String searchPath = text_searchPath.getText();
                String searchName = text_FileName.getText();
                if (StrUtil.isNotEmpty(searchPath)) {
                    tableView.getItems().clear();
                    files.clear();
                    search.setDisable(true);
                    text_FileName.setDisable(true);
                    try {
                        fileTask.init(searchPath, searchName);
                        fileTask.getState();
                        fileTask.reset();
                        fileTask.start();
                        Dialog("SUCCESS", "检索完毕", primaryStage, Alert.AlertType.INFORMATION);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Dialog("ERROR", "错误：" + e.getMessage(), primaryStage, Alert.AlertType.ERROR);
                    } finally {
                        search.setDisable(false);
                        text_FileName.setDisable(false);
                    }
                } else
                    Dialog("WARING", "请输入检索条件", primaryStage, Alert.AlertType.WARNING);
            }
        });

        //开始移动文件到文件夹
        copy.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                String fileName = text_Filepath.getText();
                String searchName = text_FileName.getText();
                if (files.size() == 0) {
                    Dialog("WARING", "没有可移动的文件啦", primaryStage, Alert.AlertType.WARNING);
                } else if (StrUtil.isNotEmpty(fileName) && StrUtil.isNotEmpty(searchName)) {
                    try {
                        String path = fileName + java.io.File.separator + searchName;
                        FileUtil.mkdir(path);
                        files.forEach(q -> {
                            FileUtil.move(FileUtil.file(q.getFilePath()), FileUtil.file(path), true);
                        });
                        Dialog("SUCCESS", "移动完毕", primaryStage, Alert.AlertType.INFORMATION);
                        files.clear();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else
                    Dialog("WARING", "请输入移动的路径", primaryStage, Alert.AlertType.WARNING);
            }
        });
    }

    @Override
    public void stop() throws Exception {
        super.stop();
    }


    /**
     * 弹窗
     *
     * @param p_header
     * @param p_message
     */
    public void Dialog(String p_header, String p_message, Stage stage, Alert.AlertType alertType) {
        Alert _alert = new Alert(alertType);
        _alert.setTitle("信息");
        _alert.setHeaderText(p_header);
        _alert.setContentText(p_message);
        _alert.initOwner(stage);
        _alert.show();
    }

}
